<?php 
final class Sms
{
	/**
	 * @var ISms
	 */
	private $_sms;
	public $name;
	private $conf;
	private $configArray;
	
	function __construct(array $conf)
	{
		if (empty($conf['use']) || empty($conf[$conf['use']])) {
			throw new Exception('sms.u_configWrong');
		}
		$this->name = $conf['use'];
		$this->conf = $conf[$this->name];
		$this->configArray = $conf;
		if(!empty($conf['channel']))
		{
			$this->name = $conf['channel'];
		}
	}

	/**
	*设置短信通道(useName必须在配置文件中配置)
	*/
	function setUse($useName)
	{
		if (empty($this->configArray[$useName]))
		{
			throw new Exception('sms.u_configName not found');
		}
		$this->name = $useName;
		$this->conf = $this->configArray[$useName];
		if(!empty($this->conf['channel']))
		{
			if(!empty($this->configArray[$this->conf['channel']]))
			{
				$this->name = $this->conf['channel'];
				$this->conf = $this->configArray[$this->conf['channel']];
			}
		}
	}
	
	/**
	 * 发送短信
	 * @param $msg
	 * @param $phone
	 * @return boolean
	 */
	function send($msg, $phone)
	{
		return $this->getSender()->send($msg, $phone);
	}
	
	/**
	 * 获取剩余短信条数
	 */
	function getBalance()
	{
		return $this->getSender()->getBalance();
	}
	
	/**
	 * 检查剩余短信情况
	 */
	function checkBalance()
	{
		return $this->getSender()->checkBalance();
	}
	
	/**
	 * 获取发送者
	 * @return ISms
	 */
	private function getSender()
	{
		if (!$this->_sms) {
			$name = ucfirst($this->name).'Sms';
			$path = dirname(__FILE__).'/impl/'.$name.'.php';
			if (!is_file($path)) {
				throw new Exception('sms.implNotFound name='.$name);
			}
			require_once $path;
			$this->_sms = new $name($this->conf);
		}
		return $this->_sms;
	}
}
